//
//  OAuthViewController.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/6/27.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController ,UIWebViewDelegate{
    //定义常量
    
    private let WB_Client_ID = "137942118"
    private let WB_Redirect_URL = "http://www.baidu.com"
    private let WB_Redirect_URLs = "https://www.baidu.com"
    private let WB_Secret = "56f4cfe223aa67fe0ec90f9722c9624b"
    
    
    //加载授权页面
 lazy var webView:UIWebView? = {
        let v = UIWebView()
        v.delegate = self
        return v
    }()
    
    override func loadView() {
        
        view = webView
        
       title = "新浪微博"
        
      navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
        func close(){
            SVProgressHUD.dismiss()
            dismissViewControllerAnimated(true, completion: nil)
        }
    
    override func viewDidLoad() {
        //加载页面
        loadOAuthPage()
        
    }
    
    
    //加载授权页面
    private func loadOAuthPage(){
        let  urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL)"
        let url = NSURL(string: urlString)!
        webView?.loadRequest(NSURLRequest(URL: url))
        
        
        
    }
    //MARK :- 代理方法
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //取出完整字符串
       let urlString = request.URL!.absoluteString
        //1.如果不是回调的URL,就继续加载
        print(urlString)
        if !urlString.hasPrefix(WB_Redirect_URL){
        return true
        }
        
        print("需要判断")
        let query = request.URL!.query!
        print("------\(query)")
        let codeStr = "code="
        if query.hasPrefix(codeStr){
            print("获取授权码")
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print(code)
            
            loadAccessToken(code)
        }else{
            print("取消授权")
            close()
        }
        
        return false
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func  webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //使用授权码加载token
    private func loadAccessToken(code:String){
        //url
        let    urlString = "oauth2/access_token"
        let    params = ["client_id":WB_Client_ID,"client_secret":WB_Secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_Redirect_URL]
        
        //发起网络请求
        //设置数据响应格式
            NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            //字典转模型
            //加载用户信息
            UserAccount(dict: JSON as![String :AnyObject]).loadUserInfo{(account,error) -> () in
                //判断账户信息是否正确
                if account != nil
                    
                {print(account)
                    
                sharedUserAccount = account
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVcNotification, object: false)
                //关闭当前控制器
                    self.close()
                    return}
                print(error)
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
                
                }
                
            //account.saveAccount()
            }) { (_, error) -> Void in
            print(error)
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
        }
        
        
    }
    
    deinit{
        print("------------->88")
    }
    
        
    }
    
    
    
    

